<template>
  <div class="app-container">
    <div class="filter-container query">
      <el-form :model="listQuery" label-position="right" label-width="120px">
        <el-row :gutter="10">
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model="listQuery.companyName" @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="企业类型" prop="companyType">
              <el-select v-model="listQuery.companyType" clearable filterable placeholder="请选择企业类型">
                <el-option
                  v-for="item in companyTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-form-item label="启用标记" prop="enableFlag">
              <el-select v-model="listQuery.enableFlag" clearable class="filter-item">
                <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :lg="6">
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="success" size="small" icon="el-icon-circle-plus-outline" @click="handleCreate">
              新增
            </el-button>
            <el-button type="info" icon="el-icon-refresh" size="small" @click="handleReset">
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-table
      :loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;height: 100%;"
      size="small"
      @sort-change="sortChange"
    >
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="企业名称" prop="companyName" sortable="custom" width="250" header-align="center" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.companyName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用标记" prop="enableFlag" :formatter="formatter" width="130" header-align="center" align="center" />
      <el-table-column label="公司类型" prop="companyType" :formatter="formatter" width="130" header-align="center" align="center" />
      <el-table-column label="能否修改金额" prop="canEdit" :formatter="formatter" width="130" header-align="center" align="center" />
      <el-table-column label="能否多次提交" prop="canBatch" :formatter="formatter" width="130" header-align="center" align="center" />
      <el-table-column label="创建时间" prop="createAt" width="200" header-align="center" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createAt }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" size="small" @pagination="getList" />

    <el-dialog :title="dialogFormVisible[dialogStatus]" :visible.sync="dialogFormVisible" top="10vh" width="520px" :close-on-click-modal="false" :close-on-press-escape="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" class="form-center">
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="temp.companyName" maxlength="128" />
        </el-form-item>
        <el-form-item label="启用标记" prop="enableFlag">
          <el-select v-model="temp.enableFlag" placeholder="启用标记" clearable>
            <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业类型" prop="companyType" v-if="dialogStatus == 'create'">
          <el-select v-model="temp.companyType" placeholder="企业类型" clearable>
            <el-option v-for="item in companyTypeOptions" :key="item.value" :label="item.label" :value="Number(item.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="对应清分公司" prop="outsourcingId" v-if="temp.companyType == '1'">
          <el-select v-model="temp.outsourcingId" placeholder="对应清分公司" clearable>
            <el-option v-for="item in thirdList" :key="item.id" :label="item.companyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="能否修改金额" prop="canEdit" v-if="temp.companyType == '2'">
          <el-select v-model="temp.canEdit" placeholder="能否修改金额" clearable>
            <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="能否多次提交" prop="canBatch" v-if="temp.companyType == '1'">
          <el-select v-model="temp.canBatch" placeholder="能否多次提交" clearable>
            <el-option v-for="item in enableFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button :loading="submiting" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSmskCompanyList, createSmskCompanyInfo, updateSmskCompanyInfo, deleteSmskCompanyInfo } from '@/api/smsk/company'
import Pagination from '@/components/Pagination'
import { setOptionData, valueFormate } from '@/utils/dict'

export default {
  name: 'SmskCompany',
  components: { Pagination },
  data() {
    return {
      enableFlagOptions: [],
      companyTypeOptions: [],
      list: [],
      thirdList:[],
      total: 0,
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        companyName: '',
        enableFlag: '',
        sortField: undefined,
        sortOrder: undefined,
        companyType:''
      },
      temp: {
        id: null,
        companyName: '',
        enableFlag: '',
        companyType: '', //公司类型 1：企业 2：清分
        needOutsource:false //是否需要清分公司公司处理
      },
      dialogTitleMap: {
        create: '新建上门收款企业信息',
        update: '更新上门收款企业信息'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        companyName: [{ required: true, max: 128, message: '企业名称最大长度不能超过128个字符', trigger: 'change' }],
        enableFlag: [{ required: true, message: '启用标记不能为空', trigger: 'change' }],
        companyType: [{ required: true, message: '企业类型不能为空', trigger: 'change' }],
        outsourcingId: [{ required: true, message: '第三方公司不能空', trigger: 'blur' }],
        canEdit: [{ required: true, message: '能否修改金额不能为空', trigger: 'blur' }],
        canBatch: [{ required: true, message: '能否多次提交不能为空', trigger: 'blur' }]
      },
      submiting: false
    }
  },
  created() {
    // 加载下拉数据
    const optionsMap = new Map()
    optionsMap.set('YES_OR_NO', this.enableFlagOptions)
    optionsMap.set('BASE_COMPANY_TYPE', this.companyTypeOptions)
    setOptionData(optionsMap)
    console.log(this.companyTypeOptions)
    this.getList()
    this.getThirdCompList();
  },
  methods: {
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    getList() {
      this.listLoading = true
      getSmskCompanyList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }, response => {
        this.listLoading = false
      })
    },
    getThirdCompList(){
      this.listLoading = true
      const params = {
        pageSize: -1,
        companyName: '',
        enableFlag: '',
        sortField: undefined,
        sortOrder: undefined,
        companyType:'2'
      }
      getSmskCompanyList(params).then(response => {
        this.thirdList = response.data
        this.total = response.total
        this.listLoading = false
      }, response => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        companyName: '',
        enableFlag: ''
      }
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: null,
        companyName: '',
        enableFlag: '',
        companyType: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submiting = true
          if(this.temp.companyType == '1'){
            this.temp.needOutsource = true
          }
          createSmskCompanyInfo(this.temp).then(response => {
            this.submiting = false
            this.dialogFormVisible = false
            this.getList()
            this.$message({
              message: '企业信息保存成功!',
              type: 'success'
            })
          }, () => {
            this.submiting = false
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submiting = true
          updateSmskCompanyInfo(this.temp).then(response => {
            this.submiting = false
            this.getList()
            this.dialogFormVisible = false
            this.$message({
              message: '企业信息更新成功!',
              type: 'success'
            })
          }, () => {
            this.submiting = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认',
        message: '确认删除企业[' + row.companyName + ']?',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteSmskCompanyInfo(row.id).then((response) => {
              this.getList()
              this.$message({
                message: '企业[' + row.companyName + ']删除成功!',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      })
    }

  }
}
</script>
